package com.wang.auth.service.impl;

import com.wang.auth.service.SysMenuService;
import com.wang.auth.service.SysUserService;
import com.wang.model.system.SysLoginLog;
import com.wang.model.system.SysUser;
import com.wang.security.custom.CustomUser;
import com.wang.security.custom.UserDetailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author wjh
 * @create 2023-05-27
 */
@Service
public class UserDetailsServiceImpl implements UserDetailService {

    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysUserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getUserByUserName(username);
        if (user == null)
            throw new UsernameNotFoundException("用户名不存在！");
        if (user.getStatus() == 0)
            throw new RuntimeException("账号已停用！");
        //根据userid查询用户操作权限数据
        List<String> perms = menuService.findUserPermsByUserId(user.getId());
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String perm : perms) {
            //trim()方法实际上的行为并不是”去掉两端的空白字符“，而是截取中间的非空白字符
            grantedAuthorities.add(new SimpleGrantedAuthority(perm.trim()));
        }

        return new CustomUser(user, grantedAuthorities);
    }


}
